package com.example.shushiyunsst.fragment.main.home.child.miner22

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.*
import androidx.appcompat.widget.Toolbar
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.base.LazyFragment
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_LIST
import com.example.library_common.view.nice_spinner.NiceSpinner
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.home.child.miner22.bean.CMLIntent
import com.example.shushiyunsst.fragment.main.wallet.sub.TransferFragment
import com.example.shushiyunsst.fragment.main.wallet.sub.WalletHeadFragment
import com.example.shushiyunsst.scan.ScanFrameFragment
import com.example.shushiyunsst.scan.ScanResListener
import com.example.shushiyunsst.util.PayingPassWordVerifyPop
import com.example.wallet.bean.BalanceInfoBean
import com.example.wallet.db.BalanceInfoManager
import com.example.wallet.db.UserInfoManager
import com.example.wallet.global.AppGlobals
import com.example.wallet.utils.selectorIcon
import com.example.wallet.utils.selectorMotherIcon
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.senon.modularapp.util.JssSpannableString
import org.greenrobot.eventbus.EventBus
import java.math.BigDecimal

class CMLTransferFragment : LazyFragment(), View.OnClickListener,
    RadioGroup.OnCheckedChangeListener {

    companion object {


        /**
         * @param mCMLIntent  转出地址账户类型
         * */
        fun newInstance(mCMLIntent: CMLIntent): CMLTransferFragment {
            val args = Bundle()
            args.putSerializable("mCMLIntent", mCMLIntent)

            val fragment = CMLTransferFragment()
            fragment.arguments = args
            return fragment
        }

        //自由母币
        const val ZI_YOU = 1

        //合成母币
        const val HE_CHEN = 0

    }


    private var mCMLIntent: CMLIntent? = null

    private var moneyType = AppGlobals.getApplication().getString(R.string.wallet_cml)

    private lateinit var feedingTv: TextView

    private lateinit var moneyTv: TextView

    private lateinit var addressTv: EditText;

    private lateinit var availableCount: EditText

    private lateinit var txTypeRadioGroup: RadioGroup

    private lateinit var mCMLAllCaptureFragment: CMLAllCaptureFragment

    private var realBalance = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
        mCMLIntent = arguments?.getSerializable("mCMLIntent") as CMLIntent
        moneyType = mCMLIntent?.iconType ?: ""

    }

    override fun getLayoutId(): Any {
        return R.layout.cml_trans_fer_fragment
    }

    override fun lazyInit() {
//        val balanceInfoBean = BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()
//        if (balanceInfoBean == null) {
//            getUserBalanceInfo(_mActivity)
//            return
//        }
        presentBalanceInfo()
    }

    private fun presentBalanceInfo() {
        val availableValue = mCMLIntent?.cmlCount ?: ""
        val feeBeanBean = BalanceInfoManager.mBalanceInfoManager.getFeeBeanBean()
        val minerFees = feeBeanBean?.cml
        val spn = JssSpannableString(
            _mActivity,
            "可用${availableValue} ${mCMLIntent?.iconType} ,矿工费: ${minerFees}$moneyType"
        )
            .first(availableValue).textColor(R.color.PrimaryColor)
            .first(minerFees.toString()).textColor(R.color.PrimaryColor)


        feedingTv.text = spn
    }

    override fun initView(view: View) {
        feedingTv = view.findViewById(R.id.feedingTv)

        addressTv = view.findViewById(R.id.addressTv)

        txTypeRadioGroup = view.findViewById(R.id.txTypeRadioGroup)

        txTypeRadioGroup.setOnCheckedChangeListener(this)

//        addressTv.setText(mCMLIntent?.address)

        availableCount = view.findViewById(R.id.availableCount)

        moneyTv = view.findViewById(R.id.moneyTv)

        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        moneyTv.text = moneyType

        mCMLAllCaptureFragment = CMLAllCaptureFragment.newInstance(mCMLIntent)

        loadRootFragment(R.id.wallet_header, mCMLAllCaptureFragment)

        view.findViewById<View>(R.id.mSaner)
            .setOnClickListener {
                val newInstance = ScanFrameFragment.newInstance()
                newInstance.setScanResListener(object : ScanResListener {
                    override fun onResStr(resStr: String) {
                        Toast.makeText(_mActivity, resStr, Toast.LENGTH_SHORT).show()
                    }
                })
                start(newInstance)
            }


        if (mCMLIntent?.transferType == CMLIntent.MOTHER_ACCOUNT
            && (mCMLIntent?.accountType ?: "").contains(_mActivity.getString(R.string.wallet_cml))
        ) {
            txTypeRadioGroup.visibility = View.VISIBLE
            querySCmlBalance()
        } else {
            txTypeRadioGroup.visibility = View.GONE
        }

        view.findViewById<View>(R.id.sureTv).setOnClickListener(this)

        view.findViewById<View>(R.id.mSaner).setOnClickListener(this)

        view.findViewById<View>(R.id.forAll).setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.forAll -> {

                availableCount.setText(mCMLIntent?.cmlCount)
            }

            R.id.mSaner -> {
                val newInstance = ScanFrameFragment.newInstance()
                newInstance.setScanResListener(object : ScanResListener {
                    override fun onResStr(resStr: String) {
                        addressTv.setText(resStr)
                    }
                })
//                supportDelegate.start(newInstance)
                start(newInstance)
            }
            R.id.sureTv -> {
                if (!checkInfo()) {
                    return
                }
                val mPop = PayingPassWordVerifyPop(_mActivity)
                XPopup.Builder(_mActivity)
                    .setPopupCallback(object : SimpleCallback() {
                        override fun onDismiss(popupView: BasePopupView?) {
                            super.onDismiss(popupView)
                            if (mPop.getIsOnVerifyPop()) {
                                if (mPop.getVerifyPop()) {
                                    if (mCMLIntent?.transferType == CMLIntent.MOTHER_ACCOUNT) {
                                        sendMotherIcon()
                                    } else {
                                        Log.d("onDismiss", "onDismiss: ${mCMLIntent?.accountType}")
                                        when (mCMLIntent?.accountType) {
                                            _mActivity.getString(R.string.wallet_cml) -> {
                                                sendSCmlAll()
                                            }

                                            _mActivity.getString(R.string.wallet_arl) -> {
                                                sendSArl()
                                            }
                                        }

                                    }

                                } else {
                                    Toast.makeText(_mActivity, "支付密码错误", Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    })
                    .asCustom(mPop)
                    .show()

            }
        }
    }

    private fun sendSArl() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val toAddr = addressTv.text.toString()
        val txNums = availableCount.text.toString()
        val map = mapOf(
            "uid" to userInfo?.uid,
            "toAddr" to toAddr,
            "fromAddr" to mCMLIntent?.address,
            "txNums" to txNums,
            "isChildAccTxOut" to mCMLIntent?.transferType
        )

        RestClient.builder()
            .url(R.string.transferARL)
            .raw(JSON.toJSONString(map))
            .success {
                Toast.makeText(_mActivity, "转账成功", Toast.LENGTH_SHORT).show()
                getUserBalanceInfo(_mActivity)
                EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_LIST))
                onBackPressedSupport()
            }
            .failure {
                Toast.makeText(_mActivity, "转账失败", Toast.LENGTH_SHORT).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.build().post()
    }

    private fun txType(): Int {
        return when (txTypeRadioGroup.checkedRadioButtonId) {
            R.id.ziYou -> ZI_YOU
            R.id.heChen -> HE_CHEN
            else -> ZI_YOU
        }
    }

    private fun sendMotherIcon() {

        val toAddr = addressTv.text.toString()
        val txNums = availableCount.text.toString()
        val map = mapOf(
            "toAddr" to toAddr,
            "fromAddr" to mCMLIntent?.address,
            "txNums" to txNums,
            "tokenType" to mCMLIntent?.accountType,
            "txType" to txType()
        )

        RestClient.builder()
            .url(R.string.transferSToken)
            .raw(JSON.toJSONString(map))
            .success {
                Toast.makeText(_mActivity, "转账成功", Toast.LENGTH_SHORT).show()
                getUserBalanceInfo(_mActivity)
                EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_LIST))
                onBackPressedSupport()
            }
            .failure {
                Toast.makeText(_mActivity, "转账失败", Toast.LENGTH_SHORT).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.build().post()
    }

    private fun checkInfo(): Boolean {
        var flag = true
        val toAddr = addressTv.text.toString()
        val txNums = availableCount.text.toString()
        if (toAddr.isEmpty()) {
            Toast.makeText(_mActivity, "请输入转账地址", Toast.LENGTH_SHORT).show()
            flag = false
        }

        if (txNums.isEmpty()) {
            Toast.makeText(_mActivity, "请输入转账地址数量", Toast.LENGTH_SHORT).show()
            flag = false
        }

        return flag
    }

    private fun sendSCmlAll() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val toAddr = addressTv.text.toString()
        val txNums = availableCount.text.toString()
        val map = mapOf(
            "uid" to userInfo?.uid,
            "toAddr" to toAddr,
            "fromAddr" to mCMLIntent?.address,
            "txNums" to txNums,
            "isChildAccTxOut" to mCMLIntent?.transferType
        )
        RestClient.builder()
            .url(R.string.transferCML)
            .raw(JSON.toJSONString(map))
            .success {
                Toast.makeText(_mActivity, "转账成功", Toast.LENGTH_SHORT).show()
                getUserBalanceInfo(_mActivity)
                EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_LIST))
                onBackPressedSupport()
            }
            .failure {
                Toast.makeText(_mActivity, "转账失败", Toast.LENGTH_SHORT).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }
            .build()
            .post()
    }

    private fun querySCmlBalance() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val map = mapOf(
            "uid" to userInfo?.uid,
            "txType" to txType()
        )
        RestClient.builder()
            .url(R.string.queryScmlBalance)
            .raw(JSON.toJSONString(map))
            .success {
                val obj = JSON.parseObject(it)
                realBalance = obj["realBalance"].toString()
                mCMLIntent?.cmlCount = realBalance
                presentBalanceInfo()
                mCMLAllCaptureFragment.showRealBalance(realBalance)
            }
            .failure {
                Toast.makeText(_mActivity, "sever inter error", Toast.LENGTH_SHORT).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }
            .build()
            .post()
    }

    override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
        querySCmlBalance()
    }
}